using System.Web;
using System.Web.Mvc;
using Azure.Web.Models;

using Azure.Domain.Services;

namespace Azure.Web.Controllers
{
    [HandleError]
    public class BlogController : BaseController
    {
        private readonly IBlogService _blogService;

        public BlogController(IBlogService blogService, IBlogConfiguration configuration) : base(configuration)
        {
            _blogService = blogService;
        }

        [ActionName(Blog.Latest)]
        public ActionResult Latest()
        {
            var post = _blogService.LatestPost();

            return RedirectToAction(Blog.View,
                                    Blog.Controller,
                                    new
                                        {
                                            year = post.Year(), 
                                            month = post.Month(), 
                                            day = post.Day(), 
                                            slug = post.Slug
                                        });
        }

        [ActionName(Blog.View)]
        public ActionResult View(int year, int month, int day, string slug)
        {
            ActionResult result;

            var post = _blogService.LoadPost(year, month, day, slug);
            if (post == null)
            {
                throw new HttpException(404, "Post does not exist.");
            }

            var model = new PostViewModel(post);

            result = View(model);

            return result;
        }

        [ActionName(Blog.Index)]
        public ActionResult Recent()
        {
            var posts = _blogService.Last(5);
            var model = new RecentPostsViewModel(posts);
            ActionResult result = this.View(model);

            return result;
        }
    }

    public static class Blog
    {
        public const string Controller = "Blog";
        public const string View = "view";
        public const string Latest = "latest";
        public const string Index = "index";
    }
}


